package com.bjpowernode.future;

import java.util.concurrent.*;

public class MyFutureTask {

    public static void main(String[] args) {
        /*FutureTask<String> futureTask = new FutureTask(new Callable() {
            @Override
            public String call() throws Exception {
                System.out.println(Thread.currentThread().getName());
                return "OK";
            }
        });
        //启动线程
        new Thread(futureTask).start();
        try {
            //等待任务执行完毕，并返回结果
            String result = futureTask.get();
            System.out.println(result);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }*/

        /*FutureTask<String> futureTask = new FutureTask(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName());
            }
        }, "YES");

        //启动线程
        new Thread(futureTask).start();
        try {
            //等待任务执行完毕，并返回结果
            String result = futureTask.get();
            System.out.println(result);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }*/

        FutureTask<String> futureTask = new FutureTask(new Callable() {
            @Override
            public String call() throws Exception {
                System.out.println(Thread.currentThread().getName());
                return "OK";
            }
        });
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        executorService.execute(futureTask);
        //Future<?> future = executorService.submit(futureTask);
        try {
            //等待任务执行完毕，并返回结果
            Object result = futureTask.get();
            System.out.println(result);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }

        //我们再次执行futureTask，那么就不能执行了
        //executorService.execute(futureTask); //没有任何效果
        new Thread(futureTask).start();//没有任何效果

        //关闭线程池
        executorService.shutdown();
    }
}
